package com.rinvay.network.filedownload;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.rinvay.network.filedownload.model.DownloadTask;
import com.rinvay.network.http.HttpRequest;
import com.rinvay.network.http.conn.HttpConnection;
import com.rinvay.network.http.conn.impl.HttpConnectionManager;
import com.rinvay.network.http.exception.NetWorkInvalidException;
import com.rinvay.utils.logger.Log;
import com.rinvaylabs.utils.FileUtil;

public class FileDownloadTest
{

    private static final String TAG = "FileDownloadTest";
    
    

    /**
     * @param args
     */
    public static void main(String[] args) {
        Log.i(TAG, "main");
        String url = "http://gdown.baidu.com/data/wisegame/a2d671156bc3d478/taobao.apk";
		
//        String url = "http://i2.cdn.turner.com/cnn/dam/assets/121107023622-magic-wall-map-hp-video.jpg";
//        String url = "http://pic9.nipic.com/20100911/5653289_201948653295_2.jpg";
//        String url = "http://pic9.nipic.com/20100911/5653289_201948653295_2.jpg";
        String path = "file/download/";
        FileDownloadManager fdmgr = new FileDownloadManager();
//        fdmgr.addListener(null);
//        DownloadTask task = new DownloadTask(url, path, "5653289_201948653295_2.jpg", 3);
        DownloadTask task = new DownloadTask(url, path, "tao.apk", 3);
        fdmgr.startResourceDownload(task);
        
//        getFileNameFromUrl();
    }
    
    private static void getFileNameFromUrl() {
        String url = "http://i2.cdn.turner.com/cnn/dam/assets/121107023622-magic-wall-map-hp-video.jpg";
//        String url = "http://dt.sheldons.i/COFFdD0xMzQ2NjU2MjgyJmk9MTE0LjIyMS4zOS4yMjUmdT1Tb25ncy92MS9mYWludFFDLzY1LzM3MTdiYzk3NTczYzNhOWMxOWVmNWU3ODAwZmFiNjY1LndtYSZtPTQ0NDllMmJiODU1NGM2NTAzMWMzOTZiNTBjNDEyMTdiJnY9ZG93biZuPcjnufvDu9PQxOMmcz3Wo7rnJTI2wO60+sStJnA9cw==.wma";
//        String name = "COFFdD0xMzQ2NjU2MjgyJmk9MTE0LjIyMS4zOS4yMjUmdT1Tb25ncy92MS9mYWludFFDLzY1LzM3MTdiYzk3NTczYzNhOWMxOWVmNWU3ODAwZmFiNjY1LndtYSZtPTQ0NDllMmJiODU1NGM2NTAzMWMzOTZiNTBjNDEyMTdiJnY9ZG93biZuPcjnufvDu9PQxOMmcz3Wo7rnJTI2wO60+sStJnA9cw==.wma";
//        try {
//            name = new String(name.getBytes("ISO8859-1"), "UTF-8");
//            Log.i(TAG, name);
//        } catch (UnsupportedEncodingException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
        HttpRequest req = new HttpRequest(url);
        HttpConnectionManager mgr = new HttpConnectionManager();
        HttpConnection conn = mgr.createDefaultHttpConnection(req, null);
        try {
            HttpURLConnection urlConn = conn.connect();
            String dis = urlConn.getHeaderField("Content-Disposition");
            if(dis != null) {
                String filename = parseContentDisposition(dis);
                filename = new String(filename.getBytes("ISO8859-1"), "gb2312");
                Log.i(TAG, filename);
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NetWorkInvalidException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    /** Regex used to parse content-disposition headers */
    private static final Pattern CONTENT_DISPOSITION_PATTERN = Pattern.compile(
            "attachment;\\s*filename\\s*=\\s*(\"?)([^\"]*)\\1\\s*$",
            Pattern.CASE_INSENSITIVE);

    /*
     * Parse the Content-Disposition HTTP Header. The format of the header
     * is defined here: http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html
     * This header provides a filename for content that is going to be
     * downloaded to the file system. We only support the attachment type.
     * Note that RFC 2616 specifies the filename value must be double-quoted.
     * Unfortunately some servers do not quote the value so to maintain
     * consistent behaviour with other browsers, we allow unquoted values too.
     */
    static String parseContentDisposition(String contentDisposition) {
        try
        {
            Matcher m = CONTENT_DISPOSITION_PATTERN.matcher(contentDisposition);
            if (m.find())
            {
                return m.group(2);
            }
        } catch (IllegalStateException ex)
        {
            // This function is defined as returning null when it can't parse the header
        }
        return null;
    }
}
